package com.simple.crawler.utils;

import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @ClassName DynamicClassLoader
 * @Author Administrator
 * @Desc TODO
 * @CreateTime 2019/7/6 22:32
 */
public class ClassLoaderUtils extends ClassLoader {

    private String filePath;

    private String className;

    private ClassLoaderUtils(String className, String filePath) {
        this.className = className;
        this.filePath = filePath;
    }

    public static Class<?> loadClass(String className, String filePath) {
        try {
            return Class.forName(className, true, new ClassLoaderUtils(className, filePath));
        } catch (Exception e) {
            throw new RuntimeException("class [" + className + ".class] not found");
        }
    }

    @Override
    protected Class<?> findClass(String name) {
        try {
            Path path = Paths.get(new URI(filePath));
            byte[] content = Files.readAllBytes(path);
            return defineClass(className, content, 0, content.length);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

}
